﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace SafeFile
{
    internal static class Utils
    {
        public static byte[] GetMD5(Stream stream, Action<int> callback = null)
        {
            var computer = MD5.Create();

            var buffer = new byte[1024 * 1024];

            var pos = stream.Position;
            stream.Position = 0;
            while (true)
            {
                var read = stream.Read(buffer, 0, buffer.Length);
                if (read == 0)
                {
                    break;
                }
                if (callback != null)
                {
                    callback(read);
                }
                computer.TransformBlock(buffer, 0, read, buffer, 0);
            }
            computer.TransformFinalBlock(buffer, 0, 0);

            stream.Position = pos;

            return computer.Hash;
        }

        public static string Bytes2String(byte[] bytes)
        {
            if (bytes == null)
            {
                return null;
            }
            return BitConverter.ToString(bytes, 0, bytes.Length).Replace("-", "");
        }

        public static bool Equals(byte[] a, byte[] b)
        {
            if (a == b) return true;
            if (a.Length != b.Length) return false;
            return a.SequenceEqual(b);
        }
    }
}
